﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using Coolite.Ext.Web;
using Pap.Web.Modules.Administration.ViewModel;
using Pap.Web.Utils;
using Utils.UIPermission;

namespace Pap.Web.Modules.Administration.Views
{
    /// <summary>
    /// 
    /// </summary>
    public partial class LookUpManager : BasePage<LookUpManagerViewModel>, IPermittedPage
    {
        #region  [ QueryString ]

        /// <summary>
        /// Gets the name of the table.
        /// </summary>
        /// <value>
        /// The name of the table.
        /// </value>
        public string TableName
        {
            get
            {
                return Request.QueryString["T"];
            }
        }

        /// <summary>
        /// Gets the name of the parent table.
        /// </summary>
        /// <value>
        /// The name of the parent table.
        /// </value>
        public string ParentTableName
        {
            get
            {
                return Request.QueryString["PT"];
            }
        }

        /// <summary>
        /// Gets the name of the FK.
        /// </summary>
        /// <value>
        /// The name of the FK.
        /// </value>
        public string FKName
        {
            get
            {
                string fk = Request.QueryString["FK"];
                if (fk.IsNullOrEmpty())
                    fk = ParentTableName + "ID";
                return fk;
            }
        }

        /// <summary>
        /// Gets the display name of the table.
        /// </summary>
        /// <value>
        /// The display name of the table.
        /// </value>
        public string TableDisplayName
        {
            get
            {
                return Server.UrlDecode(Request.QueryString["TD"]);
            }
        }

        /// <summary>
        /// Gets the display name of the parent.
        /// </summary>
        /// <value>
        /// The display name of the parent.
        /// </value>
        public string ParentDisplayName
        {
            get
            {
                return Server.UrlDecode(Request.QueryString["PD"]);
            }
        }

        /// <summary>
        /// Gets the extra params.
        /// </summary>
        public Dictionary<string, string> ExtraParams
        {
            get
            {
                Dictionary<string, string> extraParams = new Dictionary<string, string>();
                foreach (string param in Request.QueryString.Keys)
                {
                    string p = param.ToLower();
                    if (param.ToLower() != "t" && param.ToLower() != "pt" && param.ToLower() != "td" && param.ToLower() != "pd" && param.ToLower() != "fk")
                        extraParams.Add(param, Request.QueryString[param]);
                }
                return extraParams;
            }
        }

        #endregion

        #region [ Events ]

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Ext.IsAjaxRequest && !IsPostBack)
            {
                if (!TableDisplayName.IsNullOrEmpty())
                {
                    Page.Title = TableDisplayName;
                    pnlMain.Title = TableDisplayName;
                }
                RefreshGrid();
                RefreshParentGrid();
            }
        }

        /// <summary>
        /// Handles the Click event of the btnAdd control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            ShowWindow();
        }

        /// <summary>
        /// Handles the Command event of the gvTable control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void gvTable_Command(object sender, AjaxEventArgs e)
        {
            if (e.ExtraParams["CommandName"] == "Edit")
            {
                string id = e.ExtraParams["ID"];
                string name = e.ExtraParams["Name"];
                string pId = e.ExtraParams["PID"];

                ShowWindow(id, name, pId);
            }
        }

        /// <summary>
        /// Handles the Clicked event of the wndbtnSubmit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void wndbtnSubmit_Clicked(object sender, AjaxEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(wndtxtID.Text))
                {
                    Dictionary<string, string> extraParams = this.ExtraParams;
                    //add
                    if (extraParams.Count == 0)
                    {
                        if (ParentTableName.IsNullOrEmpty())
                            this.ViewModel.Insert(TableName, wndtxtName.Text);
                        else this.ViewModel.Insert(TableName, wndtxtName.Text, FKName, cmbParent.SelectedItem.Value.ToGuid());
                    }
                    else
                    {
                        this.ViewModel.Insert(TableName, wndtxtName.Text, extraParams);
                    }
                }
                else
                {
                    //edit
                    if (ParentTableName.IsNullOrEmpty())
                        this.ViewModel.Update(TableName, wndtxtID.Text.ToGuid(), wndtxtName.Text);
                    else this.ViewModel.Update(TableName, wndtxtID.Text.ToGuid(), wndtxtName.Text, FKName, cmbParent.SelectedItem.Value.ToGuid());
                }
                ShowDoneMSG();
            }
            catch (Exception exp)
            {
                ShowErrorMSG();
                HideWindow();
            }
            HideWindow();

            RefreshGrid();
        }

        /// <summary>
        /// Handles the Clicked event of the wndbtnCancel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void wndbtnCancel_Clicked(object sender, AjaxEventArgs e)
        {
            HideWindow();
        }

        /// <summary>
        /// Handles the Refresh event of the TableStore control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.StoreRefreshDataEventArgs"/> instance containing the event data.</param>
        protected void TableStore_Refresh(object sender, StoreRefreshDataEventArgs e)
        {
            RefreshGrid();
        }


        #endregion

        #region [ Functions ]

        /// <summary>
        /// Deletes the selected entites.
        /// </summary>
        /// <param name="btn">The BTN.</param>
        [AjaxMethod]
        public void DeleteSelectedEntites(string btn)
        {
            if (btn == "yes")
            {
                try
                {
                    RowSelectionModel sm = this.gvTable.SelectionModel.Primary as RowSelectionModel;
                    List<Guid> selected = sm.SelectedRows.Select(row => row.RecordID.ToGuid()).ToList();

                    this.ViewModel.Delete(TableName, selected);
                    ShowDeleteDoneMSG();
                    HideWindow();

                    RefreshGrid();
                }
                catch
                {
                    ShowErrorMSG();
                    HideWindow();
                }
            }
        }

        /// <summary>
        /// Refreshes the grid.
        /// </summary>
        protected void RefreshGrid()
        {
            if (this.ViewModel != null && !TableName.IsNullOrEmpty())
            {
                if (ParentTableName.IsNullOrEmpty())
                {
                    TableStore.DataSource = this.ViewModel.GetAll(TableName);
                    TableStore.DataBind();
                }
                else
                {
                    TableStore.DataSource = this.ViewModel.GetAll(TableName, ParentTableName, FKName);
                    TableStore.DataBind();
                }
            }
        }

        /// <summary>
        /// Refreshes the parent grid.
        /// </summary>
        protected void RefreshParentGrid()
        {
            if (this.ViewModel != null && !TableName.IsNullOrEmpty())
            {
                ColumnBase parentColumn = gvTable.ColumnModel.Columns.Single(column => column.ColumnID == "ParentColumn");
                if (ParentTableName.IsNullOrEmpty())
                {
                    parentColumn.Hidden = true;
                }
                else
                {
                    ParentTableStore.DataSource = this.ViewModel.GetAll(ParentTableName);
                    ParentTableStore.DataBind();

                    parentColumn.Header = ParentDisplayName;
                }
            }
        }

        /// <summary>
        /// Shows the window.
        /// </summary>
        private void ShowWindow()
        {
            wndtxtID.Reset();
            wndtxtName.Reset();
            if (ParentTableName.IsNullOrEmpty())
            {
                cmbParent.Hidden = true;
                cmbParent.AllowBlank = true;
            }
            else
            {
                cmbParent.Hidden = false;
                cmbParent.FieldLabel = ParentDisplayName;
                cmbParent.AllowBlank = false;
                cmbParent.Reset();
            }

            wndEdit.Title = GetLocalResourceObject("TitleAdd").ToString();

            wndEdit.Expand(true);
            wndEdit.Show();
        }

        /// <summary>
        /// Shows the window.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <param name="name">The name.</param>
        /// <param name="pid">The pid.</param>
        private void ShowWindow(string id, string name, string pid)
        {
            wndtxtID.Text = id;
            wndtxtName.Text = name;
            if (pid.IsNullOrEmpty())
            {
                cmbParent.Hidden = true;
                cmbParent.AllowBlank = true;
            }
            else
            {
                cmbParent.Hidden = false;
                cmbParent.AllowBlank = false;
                cmbParent.FieldLabel = ParentDisplayName;
                cmbParent.SelectedItem.Value = pid;
            }
            wndEdit.Title = GetLocalResourceObject("TitleEdit").ToString();

            wndEdit.Show();
        }

        /// <summary>
        /// Hides the window.
        /// </summary>
        private void HideWindow()
        {
            wndEdit.Hide();
        }

        /// <summary>
        /// Shows the error MSG.
        /// </summary>
        private void ShowErrorMSG()
        {
            Ext.Msg.Configure(new MessageBox.Config
               {
                   Title = GetLocalResourceObject("MBErrorCaption").ToString(),
                   Message = GetLocalResourceObject("MBErrorMSG").ToString(),
                   Icon = MessageBox.Icon.ERROR,
                   Buttons = MessageBox.Button.OK
               }).Show();
        }

        /// <summary>
        /// Shows the done MSG.
        /// </summary>
        protected void ShowDoneMSG()
        {
            Ext.Msg.Configure(new MessageBox.Config
            {
                Title =
                GetLocalResourceObject("MBDoneCaption").ToString(),
                Message = GetLocalResourceObject("MBDoneMSG").ToString(),
                Buttons = MessageBox.Button.OK,
                Icon = MessageBox.Icon.INFO
            }).Show();
        }

        /// <summary>
        /// Shows the delete done MSG.
        /// </summary>
        protected void ShowDeleteDoneMSG()
        {
            Ext.Msg.Configure(new MessageBox.Config
            {
                Title =
                GetLocalResourceObject("MBDoneCaption").ToString(),
                Message = GetLocalResourceObject("MBDeleteDoneMSG").ToString(),
                Buttons = MessageBox.Button.OK,
                Icon = MessageBox.Icon.INFO
            }).Show();
        }

        #endregion

        #region IPermittedPage Members

        /// <summary>
        /// Gets the name of the permission.
        /// </summary>
        /// <value>
        /// The name of the permission.
        /// </value>
        public string PermissionName
        {
            get { return "LookUpManager"; }
        }

        #endregion
    }
}
